package com.cloud.common.util;

import org.apache.commons.lang3.StringUtils;

import java.nio.ByteBuffer;
import java.util.Base64;

/**
 * 编码工具类，可用来生成访问令牌
 */
public class CodecUtils {

	private static final int DEFAULT_VALID_TIMEE = 7 * 24 * 3600;

	/**
	 * 编码
	 * 
	 * @param value
	 * @return String
	 */
	public static String encode(String value) {
		return encode(value, DEFAULT_VALID_TIMEE);
	}

	/**
	 * 编码
	 * 
	 * @param value
	 * @param validTime
	 * @return String
	 */
	public static String encode(String value, int validTime) {
		try {
			int size = value.getBytes().length;
			if (size > 512) {
				return null;
			}
			ByteBuffer buf = ByteBuffer.allocate(size + 16);
			buf.putLong(System.currentTimeMillis() + (validTime * 1000L));
			buf.putInt(size);
			buf.put(value.getBytes());
			buf.putInt(value.hashCode());
			return Base64.getUrlEncoder().encodeToString(buf.array());
		} catch (Exception e) {
			return null;
		}
	}

	/**
	 * 解码
	 * 
	 * @param value
	 * @return String
	 */
	public static String decode(String value) {
		try {
			if (StringUtils.isEmpty(value)) {
				return null;
			}
			ByteBuffer buf = ByteBuffer.wrap(Base64.getUrlDecoder().decode(value));
			long time = buf.getLong();
			if (System.currentTimeMillis() >= time) {
				return null;
			}
			int size = buf.getInt();
			if (size > 512) {
				return null;
			}
			byte[] data = new byte[size];
			buf.get(data);
			String uid = new String(data);
			if (uid.hashCode() == buf.getInt()) {
				return uid;
			}
			return null;
		} catch (Exception e) {
			return null;
		}
	}

}
